﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PUCLibrary
{
    /// <summary>
    /// Clase singleton que loggea errores.
    /// </summary>
    public class Logger
    {
        //fields:
        private List<string> messages;
        private int lastReset;  //Para resetear el contador de errores
        public event Action<string> MessageAdded;

        //static fields
        private static Logger log;
        private static object syncObj = new object();

        /// <summary>
        /// Retorna la instancia singleton del logger.
        /// </summary>
        public static Logger Instance
        {
            get
            {
                if (log == null)
                {
                    //Check de multithreading
                    lock (syncObj)
                    {
                        if (log == null)
                        {
                            //Creamos nueva instancia
                            log = new Logger();
                        }
                    }
                }
                //Retornamos:
                return log;
            }
        }

        /// <summary>
        /// Retorna el total de errores desde que se inicio el Logger.
        /// </summary>
        public int ErrorCount
        {
            get
            {
                return messages.Count - lastReset;
            }
        }

        //Constructor.
        private Logger()
        {
            messages = new List<string>();
            lastReset = 0;
        }

        /// <summary>
        /// Agrega un mensaje al log.
        /// </summary>
        public void Log(string message)
        {
            messages.Add(message + "\r\n\r\n");
            //Llamamos evento:
            OnMessageAdded();
        }

        /// <summary>
        /// Agrega un mensaje al log.
        /// </summary>
        public void Log(string message, Exception err)
        {
            messages.Add(message + "\r\n-Detalle:" + err.Message + "\r\n\r\n");
            //Llamamos evento:
            OnMessageAdded();
        }

        /// <summary>
        /// Resetea el contador de errores totales.
        /// </summary>
        public void ErrorCountReset()
        {
            lastReset = messages.Count;
        }

        private void OnMessageAdded()
        {
            if (MessageAdded != null)
                MessageAdded(messages[messages.Count-1]);
        }
    }
}
